package xiaohong.algorithm;

import java.util.Arrays;
import java.util.List;

public class LongestConsecutive {

    /**
     * 给定一个未排序的整数数组 nums ，找出数字连续的最长序列（不要求序列元素在原数组中连续）的长度。
     * 请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
     *
     * 示例 1：
     * 输入：nums = [100,4,200,1,3,2]
     * 输出：4
     * 解释：最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4
     * @param args
     */
    public static void main(String[] args) {
        int[] arr = { 1, 2, 6, 7, 8, 9, 10 ,2};
        System.out.println(longestConsecutive(arr));
        System.out.println(longestConsecutive2(arr));
    }

    public static int longestConsecutive(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        Arrays.sort(nums);
        int longest = 1;
        int cur = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == nums[i - 1]) continue;
            if (nums[i] - nums[i - 1] == 1) {
                longest = Math.max(longest, ++cur);
            }else {
                cur = 1;
            }
        }
        return longest;
    }


    public static int longestConsecutive2(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }
        if (nums.length == 1) {
            return 1;
        }
        Arrays.sort(nums);
        int temp= 1;
        int max = 0;
        // 1,2,3,4,100,200
        for (int i = 0; i < nums.length-1; i++) {
            if (nums[i]+1 == nums[i + 1]) {
                temp++;
            }
            if (nums[i] == nums[i + 1]) {
                max = Math.max(temp, max);
                continue;
            }
            if (nums[i] + 1 != nums[i+1]){
                temp=1;
            }
            max=Math.max(temp,max);
        }
        return max;
    }



}
